package main

import (
	"fmt"
	"unicode"
	"unicode/utf8"
)

const SPACE = ' '

func main() {
	b := []byte("哈哈  哈 哈哈    	a")
	//b = replace(b)
	//fmt.Printf("%s\n", b)

	fmt.Printf("%s\n", removeDupBlank(b))
}

func removeDupBlank(s []byte) []byte {
	last, index := utf8.DecodeRune(s[0:])
	for i := index; i < len(s); {
		decodeRune, size := utf8.DecodeRune(s[i:])
		if !unicode.IsSpace(decodeRune) {
			if index != i {
				// 把当前字符往前移
				copy(s[index:], s[i:i+size])
			}
			i += size
			index += size
			last = decodeRune
			continue
		}
		if !unicode.IsSpace(last) {
			// 在index处加入一个空格符
			s[index] = SPACE
			index++
			last = decodeRune
		}
		i += size
	}
	return s[:index]
}

func replace(b []byte) []byte {
	for i := 0; i < len(b); {
		first, size := utf8.DecodeRune(b[i:])
		if unicode.IsSpace(first) {
			second, _ := utf8.DecodeRune(b[i+size:])
			if unicode.IsSpace(second) {
				copy(b[i:], b[i+size:])
				b = b[:len(b)-size]
			}
		}
		i += size
	}
	return b
}
